package com.servlet;

import com.common.Constant;
import com.ztc.Spider;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by ztc on 15-12-30.下午8:52
 */
public class yzmServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession(true);
        Spider spider=(Spider)session.getAttribute("spider");
        if(spider==null){
            spider=Spider.getSpider();
            session.setAttribute("spider", spider);
        }
        HttpGet hg=new HttpGet(Constant.yzmUrl+Math.random());
        try {
            CloseableHttpResponse res=spider.getClient().execute(hg);
            HttpEntity he=res.getEntity();
            InputStream is=he.getContent();
            OutputStream os=response.getOutputStream();
            BufferedImage bi= ImageIO.read(is);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");
            ImageIO.write(bi,"gif",os);
            //注意资源的关闭
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
